<template>
    <div class="layout">
      <!-- 侧边导航栏 -->
      <el-menu default-active="1" class="sidebar">
        <el-menu-item index="0" @click="goTo('/welcome')">
          <span>欢迎页面</span>
        </el-menu-item>
        <el-menu-item index="1" @click="goTo('/users')">
          <span>用户管理</span>
        </el-menu-item>
        <el-menu-item index="2" @click="goTo('/permissions')">
          <span>权限管理</span>
        </el-menu-item>
        <el-menu-item index="3" @click="goTo('/products')">
          <span>商品管理</span>
        </el-menu-item>
        <el-menu-item index="4" @click="goTo('/orders')">
          <span>订单管理</span>
        </el-menu-item>
        <el-menu-item index="5" @click="goTo('/statistics')">
          <span>数据统计</span>
        </el-menu-item>
        <el-menu-item index="6" @click="logout">
          <span>退出登录</span>
        </el-menu-item>
      </el-menu>
  
      <!-- 主内容区域 -->
      <div class="main-content">
        <div class="header">
          <h1>电商后台管理系统</h1>
        </div>
        <div class="content">
          <h2>用户管理</h2>
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
          <el-table :data="users" style="width: 100%">
            <el-table-column label="#" type="index" />
            <el-table-column prop="username" label="角色名称" />
            <el-table-column prop="role" label="角色描述" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
                <el-button type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
                <el-button type="warning" @click="viewUser(scope.row)">分配权限</el-button>
              </template>
            </el-table-column>
          </el-table>
  
          <!-- 添加用户弹窗 -->
          <el-dialog title="添加用户" v-model="dialogVisible" width="30%">
            <el-form :model="newUser" label-width="80px">
              <el-form-item label="角色名称">
                <el-input v-model="newUser.username" />
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input v-model="newUser.role" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="addUser">确定</el-button>
            </template>
          </el-dialog>
  
          <!-- 编辑用户弹窗 -->
          <el-dialog title="编辑用户" v-model="editDialogVisible" width="30%">
            <el-form :model="editUser" label-width="80px">
              <el-form-item label="角色名称">
                <el-input v-model="editUser.username" />
              </el-form-item>
              <el-form-item label="角色描述">
                <el-input v-model="editUser.role" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="editDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="updateUser">确定</el-button>
            </template>
          </el-dialog>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import axios from 'axios';
  import { useRouter } from 'vue-router';
  
  const router = useRouter();
  const users = ref([]);
  const dialogVisible = ref(false);
  const editDialogVisible = ref(false);
  const newUser = ref({ username: '', role: '' });
  const editUser = ref({ id: null, username: '', role: '' });
  
  const goTo = (path) => {
    router.push(path);
  };
  
  const fetchUsers = async () => {
    try {
      const res = await axios.get('http://localhost:3000/api/users', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      users.value = res.data;
    } catch (err) {
      ElMessage.error('获取用户列表失败');
    }
  };
  
  const addUser = async () => {
    try {
      const res = await axios.post('http://localhost:3000/api/users', newUser.value, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      users.value.push(res.data);
      dialogVisible.value = false;
      newUser.value = { username: '', role: '' };
      ElMessage.success('添加成功');
    } catch (err) {
      ElMessage.error('添加失败');
    }
  };
  
  const deleteUser = async (id) => {
    try {
      await axios.delete(`http://localhost:3000/api/users/${id}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      users.value = users.value.filter(user => user.id !== id);
      ElMessage.success('删除成功');
    } catch (err) {
      ElMessage.error('删除失败');
    }
  };
  
  const openEditDialog = (user) => {
    editUser.value = { ...user }; // 复制用户数据
    editDialogVisible.value = true;
  };
  
  const updateUser = async () => {
    try {
      const res = await axios.put(`http://localhost:3000/api/users/${editUser.value.id}`, editUser.value, {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
      });
      const index = users.value.findIndex(user => user.id === editUser.value.id);
      users.value[index] = res.data;
      editDialogVisible.value = false;
      ElMessage.success('更新成功');
    } catch (err) {
      ElMessage.error('更新失败');
    }
  };
  
  const viewUser = (user) => {
    ElMessage.info('分配权限功能待实现');
  };
  
  const logout = () => {
    localStorage.removeItem('token');
    ElMessage.success('已退出登录');
    router.push('/login');
  };
  
  onMounted(fetchUsers);
  </script>
  
  <style scoped>
  .layout {
    display: flex;
    height: 100vh;
  }
  .sidebar {
    width: 200px;
    height: 100%;
    background: #2c3e50;
    color: white;
  }
  .main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  .header {
    padding: 10px 20px;
    background: #1a252f;
    color: white;
    text-align: center;
  }
  .content {
    flex: 1;
    padding: 20px;
    background: #f0f2f5;
  }
  </style>